Home About All entries

Creating Icons with CSS Pseudo-Elements

A while ago, I wanted to add icons to my projects list. The simplest and first solution that came to my mind was to use the <img> Image Embed element for each and every icon, but it was evident this would quickly become too repetitive and unmanteinable, so I decided to try out CSS pseudo-elements.

What is a CSS pseudo-element?

A CSS pseudo-element lets you style specific parts of an element - like the first letter, list markers, or content before/after - without changing the HTML.

For my use case, I was specifically interested in the ::before pseudo-element, which can be used to insert some content before the content of an element.

For example:

.rss-icon::before {
  content: url("/images/rss-icon-32.png");
  text-align: center;
  display: block;
}

By applying this CSS, I can insert content to every div of class .rss-icon. In this case, the image /images/rss-icon-32.png

But you can also insert content ::after the content of an element. For example:

.rss-icon::after {
   content: "RSS Feed";
   display: block;
}

By combining these two pieces of CSS, all I need to do to insert this icon is to use the following HTML:

<div class="rss-icon"></div>

But I have many different RSS feeds. Conveniently, since I inserted the image using the ::before pseudo-element and the title using the ::after pseudo-element, I can "sandwich" some text in-between, like this:

<div class="rss-icon">Website Updates</div>

This is what the final result looks like.

In a scenario where these icons are used repeatedly, this makes it way easier to manage. If I ever need to change the icon, I can just modify one line of CSS and all the icons will be updated.

And that's it. Thanks for reading.